"""
    开启服务后直接127.0.0.1:7788访问:
        将会得到一个页面上面写着hello world;
"""

import socket
from multiprocessing import Process

# 有新的客户端进来就用这个函数建条进程为他服务
def handleClient(clientSocket):
    recvData = clientSocket.recv(2048)
    requestHeaderLines = recvData.splitlines()      # 客户端的请求报文
    for line in requestHeaderLines:
        print(line.decode("utf-8"))
    # 自己组响应头报文
    responseHeaderLines = "HTTP/1.1 200 OK\r\n"
    responseHeaderLines += "\r\n"
    responseBody = "hello word"                     # 自己组响应体
    response = responseHeaderLines + responseBody   # 响应报文
    clientSocket.send(response.encode("utf-8"))     # 响应回客户端(py3的send须是bytes, 所以需要encode将str转为bytes)
    clientSocket.close()                            # 响应完直接断开(短连接)

def main():
    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serverSocket.bind(("", 7788))
    serverSocket.listen(10)
    while True:
        clientSocket, clientAddr = serverSocket.accept()
        clientProcess = Process(target = handleClient, args = (clientSocket,))
        clientProcess.start()
        clientSocket.close()

if __name__ == "__main__":
    main()